<?php
/*******************************************
* Thank-o-matic
* Re-edited by Adk-Team
* www.smfpersonal.net
* 2009-2011
*******************************************/

if (!defined('SMF'))
	die('Hacking attempt...');


// The maintenance access	point.
function ManageMaintenanceThankYouPost()
{
	global $txt, $modSettings, $scripturl, $context, $options, $sourcedir;

	// You absolutely	must be	an admin by	here!
	isAllowedTo('admin_forum');

	require_once($sourcedir . '/ThankYouPost.php');

	// Need	something	to talk	about?
	loadLanguage('ManageMaintenance');
	loadTemplate('ManageMaintenance');
	loadTemplate('ThankYouPost');

	// This	uses admin tabs	-	as it	should!
	$context[$context['admin_menu_name']]['tab_data']	=	array(
		'title'	=> &$txt['maintain_thxpost'],
		'help' =>	&$txt['maintenance_general'],
		'description'	=> $txt['maintain_thank_you_post_maintainaince_desc'],
		'tabs' =>	array(
			'maintain' =>	array(
				'description'	=> $txt['maintain_thank_you_post_maintainaince_desc'],
			),
			'recount'	=> array(
				'description'	=> $txt['maintain_thank_you_post_recount_desc'],
			),
		),
	);

	// So	many things	you	can	do - but frankly I won't let you - just	these!
	$subActions	=	array(
		'maintain' =>	array(
			'function' =>	'MaintainThankYouPost',
			'template' =>	'maintain_thankYouPost',
			'activities' =>	array(
				'optimize' =>	'ThankYouPostRepairTable',
			),
		),
		'recount'	=> array(
			'function' =>	'MaintainThankYouPost',
			'template' =>	'maintain_thankYouPost_recount',
			'activities' =>	array(
				'all'	=> 'ThankYouPostRecountAll',
				'member' =>	'ThankYouPostRecountMember',
				'topic'	=> 'ThankYouPostRecountTopic',
			),
		),
	);

	// Yep,	sub-action time!
	if (isset($_REQUEST['sa']) &&	isset($subActions[$_REQUEST['sa']]))
		$subAction = $_REQUEST['sa'];
	else
		$subAction = 'maintain';

	// Doing something special?
	if (isset($_REQUEST['activity']) &&	isset($subActions[$subAction]['activities'][$_REQUEST['activity']]))
		$activity	=	$_REQUEST['activity'];

	// Set a few things.
	$context['page_title'] = $txt['maintain_thxpost'];
	$context['sub_action'] = $subAction;
	$context['sub_template'] = !empty($subActions[$subAction]['template']) ? $subActions[$subAction]['template'] : '';

	// Finally fall	through	to what	we are doing.
	$subActions[$subAction]['function']();

	// Any special activity?
	if (isset($activity))
		$subActions[$subAction]['activities'][$activity]();
}

// Supporting	function for the database	maintenance	area.
function MaintainThankYouPost()
{
	global $context, $modSettings, $smcFunc, $txt, $scripturl;

	if (!empty($_GET['done']))
	{
		if ($_GET['done']	== 'optimize')
			$context['maintenance_finished'] = &$txt['maintain_thank_you_optimize'];
		if ($_GET['done']	== 'recountall')
			$context['maintenance_finished'] = &$txt['maintain_thank_you_recountAll'];
		if ($_GET['done']	== 'member')
		{
			if (!empty($_REQUEST['id_member']) &&	is_numeric($_REQUEST['id_member']) &&	loadMemberData($_REQUEST['id_member']) !=	false)
			{
				global $memberContext;
				loadMemberContext($_REQUEST['id_member']);
				$txt['maintain_thank_you_recountMember'] = str_replace('[MEMBER]', $memberContext[$_REQUEST['id_member']]['link'], $txt['maintain_thank_you_recountMember']);
			}
			$context['maintenance_finished'] = &$txt['maintain_thank_you_recountMember'];
		}
		if ($_GET['done']	== 'topic')
		{
			global $topic;
			if (!empty($topic))
			{
				$request = $smcFunc['db_query']('',	'
					SELECT
						t.id_first_msg,	mf.subject
					FROM {db_prefix}topics AS	t
						LEFT JOIN	{db_prefix}messages	AS mf	ON (mf.id_msg	=	t.id_first_msg)
					WHERE	t.id_topic = {int:current_topic}
					LIMIT	1',
					array(
						'current_topic'	=> $topic,
					)
				);
				list ($id_first_msg, $first_subject) = $smcFunc['db_fetch_row']($request);
				$smcFunc['db_free_result']($request);

				$link	=	'<em><a	href="'	.	$scripturl . '?topic=' . $topic	.	'">' . $first_subject	.	'</a></em>';
				$txt['maintain_thank_you_recountTopic']	=	str_replace('[TOPIC]', $link,	$txt['maintain_thank_you_recountTopic']);
			}
			$context['maintenance_finished'] = &$txt['maintain_thank_you_recountTopic'];
		}
	}
}

function ThankYouPostRecountTopic()
{
	global $txt, $context, $scripturl, $modSettings, $sourcedir;
	global $time_start,	$smcFunc,	$topic;

	isAllowedTo('admin_forum');

	checkSession('request');

	$context['page_title'] = $txt['not_done_title'];
	$context['continue_post_data'] = '';
	$context['continue_countdown'] = '3';
	$context['sub_template'] = 'not_done';

	// Try for as	much time	as possible.
	@set_time_limit(600);

	// If	you	have a good	and	fast server	you	can	higher this	number,	if you have	a	slow server	reduce it	;)
	$minimumSeconds	=	3;

	if (empty($_REQUEST['start']))
		$_REQUEST['start'] = 0;

	if(empty($topic))
		redirectexit('action=admin;area=maintainThankYouPost;sa=recount');

	$total_steps = 1;

	// First recount the postdata
	if (empty($_REQUEST['step']))
	{
		$_REQUEST['step']	=	0;

		// Step	the	number of	topics at	a	time so	things don't time	out...
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_msg)
			FROM {db_prefix}thank_you_post
			WHERE	id_topic = {int:topic}',
			array(
				'topic'	=> $topic,
			)
		);

		list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_posts)
		{
			// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
			$increment = 250;

			$counter = $smcFunc['db_query']('',	'
				SELECT count(*)	as count,	id_msg
				FROM {db_prefix}thank_you_post
				WHERE	id_topic = {int:topic}
					AND	id_msg > {int:start}
					AND	id_msg <=	{int:max_id}
				GROUP	BY id_msg',
				array(
					'topic'	=> $topic,
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);

			// Update	every	post counter step	by step	:)
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
			{
				$smcFunc['db_query']('', '
					UPDATE {db_prefix}messages
					SET	thank_you_post_counter = {int:counter}
					WHERE	id_msg = {int:id_msg}
					LIMIT	{int:limit}',
					array(
						'counter'	=> $row['count'],
						'id_msg' =>	$row['id_msg'],
						'limit'	=> 1,
					)
				);
			}
			$smcFunc['db_free_result']($counter);

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=recount;activity=topic;step=0;start='	.	$_REQUEST['start'] . ';topic=' . $topic	.	';'	.	$context['session_var']	.	'='	.	$context['session_id'];
				$context['continue_percent'] = round((100	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

				return;
			}
		}
		$_REQUEST['start'] = 0;
	}

	redirectexit('action=admin;area=maintainThankYouPost;sa=recount;done=topic;topic=' . $topic);
}

function ThankYouPostRecountAll()
{
	global $txt, $context, $scripturl, $modSettings, $sourcedir;
	global $time_start,	$smcFunc;

	isAllowedTo('admin_forum');

	checkSession('request');

	$context['page_title'] = $txt['not_done_title'];
	$context['continue_post_data'] = '';
	$context['continue_countdown'] = '3';
	$context['sub_template'] = 'not_done';

	// Try for as	much time	as possible.
	@set_time_limit(600);

	// If	you	have a good	and	fast server	you	can	higher this	number,	if you have	a	slow server	reduce it	;)
	$minimumSeconds	=	3;

	if (empty($_REQUEST['start']))
		$_REQUEST['start'] = 0;

	$total_steps = 3;

	// First recount the postdata
	if (empty($_REQUEST['step']))
	{
		$_REQUEST['step']	=	0;

		// Step	the	number of	topics at	a	time so	things don't time	out...
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_msg)
			FROM {db_prefix}thank_you_post',
			array()
		);

		list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_posts)
		{
			// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
			$increment = 250;

			$counter = $smcFunc['db_query']('',	'
				SELECT count(*)	as count,	id_msg
				FROM {db_prefix}thank_you_post
				WHERE	id_msg > {int:start}
					AND	id_msg <=	{int:max_id}
				GROUP	BY id_msg',
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);

			// Update	every	post counter step	by step	:)
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
			{
				$smcFunc['db_query']('', '
					UPDATE {db_prefix}messages
					SET	thank_you_post_counter = {int:counter}
					WHERE	id_msg = {int:id_msg}
					LIMIT	{int:limit}',
					array(
						'counter'	=> $row['count'],
						'id_msg' =>	$row['id_msg'],
						'limit'	=> 1,
					)
				);
			}
			$smcFunc['db_free_result']($counter);

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=recount;activity=all;step=0;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
				$context['continue_percent'] = round((100	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

				return;
			}
		}
		$_REQUEST['start'] = 0;
	}

	// Recount all member	datas	:)
	if ($_REQUEST['step']	<= 1)
	{
		// Step	the	number of	members	at a time	so things	don't	time out...
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_member)
			FROM {db_prefix}thank_you_post',
			array()
		);

		list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_posts)
		{
			// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
			$increment = 50;
			// First reset all values	to 0 :), i use this	way	because	it's step	by step	;)
			$counter = $smcFunc['db_query']('',	'
				SELECT id_member
				FROM {db_prefix}members
				WHERE	id_member	>	{int:start}
					AND	id_member	<= {int:max_id}',
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				updateMemberData($row['id_member'],	array('thank_you_post_made'	=> 0));
			$smcFunc['db_free_result']($counter);

			$counter = $smcFunc['db_query']('',	'
				SELECT count(*)	as count,	id_member
				FROM {db_prefix}thank_you_post
				WHERE	id_member	>	{int:start}
					AND	id_member	<= {int:max_id}
				GROUP	BY id_member',
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);

			// Step	by step	update this	data,	i	will use the updatemember	data function	for	this :)
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				updateMemberData($row['id_member'],	array('thank_you_post_made'	=> $row['count']));

			$smcFunc['db_free_result']($counter);

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=maintain;activity=optimize;step=1;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
				$context['continue_percent'] = round((200	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

				return;
			}
		}
		$_REQUEST['start'] = 0;
	}

	// This	is work... hmmm	how	made this	fast?	let's	use	mageic :D
	// Okay	calculate	the	became thank yous	new	;D That	what user	give to	you...
	if ($_REQUEST['step']	<= 2)
	{
		// Step	the	number of	members	at a time	so things	don't	time out...
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_member)
			FROM {db_prefix}thank_you_post',
			array()
		);

		list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_posts)
		{
			// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
			$increment = 50;

			// First reset all values	to 0 :), i use this	way	because	it's step	by step	;)
			$counter = $smcFunc['db_query']('',	'
				SELECT id_member
				FROM {db_prefix}members
				WHERE	id_member	>	{int:start}
					AND	id_member	<= {int:max_id}',
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				updateMemberData($row['id_member'],	array('thank_you_post_became'	=> 0));
			$smcFunc['db_free_result']($counter);

			$counter = $smcFunc['db_query']('',	'
				SELECT id_member,	SUM(thank_you_post_counter)	as count
				FROM {db_prefix}messages
				WHERE	thank_you_post !=	0
					AND	id_member	>	{int:start}
					AND	id_member	<= {int:max_id}
				GROUP	BY id_member',
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);
			// Okay	replace	it :)
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				updateMemberData($row['id_member'],	array('thank_you_post_became'	=> $row['count']));

			$smcFunc['db_free_result']($counter);

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=maintain;activity=optimize;step=2;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
				$context['continue_percent'] = round((300	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

				return;
			}
		}
		$_REQUEST['start'] = 0;
	}
	// I should	find out how this	work and insert	it :D
	// Finally,	update the latest	event	times.
	// require_once($sourcedir . '/ScheduledTasks.php');
	// CalculateNextTrigger();

	redirectexit('action=admin;area=maintainThankYouPost;sa=recount;done=recountall');
}

function ThankYouPostRecountMember()
{
	global $txt, $context, $scripturl, $modSettings, $sourcedir;
	global $time_start,	$smcFunc;

	isAllowedTo('admin_forum');

	checkSession('request');

	$context['page_title'] = $txt['not_done_title'];
	$context['continue_post_data'] = '';
	$context['continue_countdown'] = '3';
	$context['sub_template'] = 'not_done';

	// Try for as	much time	as possible.
	@set_time_limit(600);

	if (empty($_REQUEST['start']))
		$_REQUEST['start'] = 0;

	$total_steps = 3;

	// Valid ID	Member?
	$_REQUEST['id_member'] = !empty($_REQUEST['id_member'])	?	(int)	$_REQUEST['id_member'] : 0;
	if(empty($_REQUEST['id_member']))
		redirectexit('action=admin;area=maintainThankYouPost;sa=recount');
	// User	exists?
	if(loadMemberData($_REQUEST['id_member'])	===	false)
		redirectexit('action=admin;area=maintainThankYouPost;sa=recount');

	$counter = $smcFunc['db_query']('',	'
		SELECT count(*)	as count,	id_member
		FROM {db_prefix}thank_you_post
		WHERE	id_member	=	{int:id_member}',
		array(
			'id_member'	=> $_REQUEST['id_member'],
		)
	);

	// Step	by step	update this	data,	i	will use the updatemember	data function	for	this :)
	while	($row	=	$smcFunc['db_fetch_assoc']($counter))
		updateMemberData($row['id_member'],	array('thank_you_post_made'	=> (int) $row['count']));
	$smcFunc['db_free_result']($counter);

	$counter = $smcFunc['db_query']('',	'
		SELECT id_member,	SUM(thank_you_post_counter)	as count
		FROM {db_prefix}messages
		WHERE	thank_you_post !=	0
			AND	id_member	=	{int:id_member}',
		array(
			'id_member'	=> $_REQUEST['id_member'],
		)
	);
	// Okay	replace	it first and than	set	up an	new	count	:D
	while	($row	=	$smcFunc['db_fetch_assoc']($counter))
		updateMemberData($row['id_member'],	array('thank_you_post_became'	=> (int) $row['count']));
	$smcFunc['db_free_result']($counter);

	redirectexit('action=admin;area=maintainThankYouPost;sa=recount;done=member;id_member='	.	$_REQUEST['id_member'] .'');
}

// Recount all the important board totals.
function ThankYouPostRepairTable()
{
	global $txt, $context, $scripturl, $modSettings, $sourcedir;
	global $time_start,	$smcFunc;

	isAllowedTo('admin_forum');

	checkSession('request');

	$context['page_title'] = $txt['not_done_title'];
	$context['continue_post_data'] = '';
	$context['continue_countdown'] = '3';
	$context['sub_template'] = 'not_done';

	// Try for as	much time	as possible.
	@set_time_limit(600);

	// If	you	have a good	and	fast server	you	can	higher this	number,	if you have	a	slow server	reduce it	;)
	$minimumSeconds	=	3;

	if (empty($_REQUEST['start']))
		$_REQUEST['start'] = 0;

	$total_steps = 5;

	// Find	all	the	not	existing Posts and remove	them from	the	thank	you	;)
	if (empty($_REQUEST['step']))
	{
		$_REQUEST['step']	=	0;

		// Step	the	number of	topics at	a	time so	things don't time	out...
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_msg)
			FROM {db_prefix}thank_you_post',
			array()
		);

		list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_posts)
		{
			// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
			$increment = 500;

			$counter = $smcFunc['db_query']('',	"
				SELECT /*!40001	SQL_NO_CACHE */	t.id_msg as	id_msg
				FROM {db_prefix}thank_you_post as	t
					LEFT JOIN	{db_prefix}messages	as m ON	(t.id_msg	=	m.id_msg)
				WHERE	m.id_msg IS	NULL
					AND	t.id_msg > {int:start}
					AND	t.id_msg <=	{int:max_id}
				GROUP	BY id_msg",
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);

			$rows	=	$smcFunc['db_num_rows']($counter);
			// Replace all
			$msg_ids = array();
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				$msg_ids[] = $row['id_msg'];

			$smcFunc['db_free_result']($counter);

			if (!empty($msg_ids))
				// Delete	all, need	no recalculation,	because	i	miss the master	things ;)
				$smcFunc['db_query']('', '
					DELETE FROM	{db_prefix}thank_you_post
					WHERE	({array_int:msg_ids})',
					array(
						'msg_ids' => $msg_ids,
					)
				);

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=maintain;activity=optimize;step=0;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
				$context['continue_percent'] = round((100	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

				return;
			}
		}
		$_REQUEST['start'] = 0;
	}

	// Find	all	the	not	existing Posts and remove	them from	the	thank	you	;)
	if ($_REQUEST['step']	<= 1)
	{
		// Load	not	enabled	list,	and	remove recycler	;D
		$boardlist = $smcFunc['db_query']('',	"
			SELECT id_board
			FROM {db_prefix}boards
			WHERE	thank_you_post_enable	!= 0 AND id_board	!= $modSettings[recycle_board]");

		$boards	=	array();
		while	($row	=	$smcFunc['db_fetch_assoc']($boardlist))
			$boards[]	=	$row['id_board'];

		// No	boards with	disable	thank	you?
		if(!empty($boards))
		{
			// Step	the	number of	topics at	a	time so	things don't time	out...
			$request = $smcFunc['db_query']('',	'
				SELECT MAX(id_msg)
				FROM {db_prefix}thank_you_post
				WHERE	id_board IN	({array_int:boards})',
				array(
					'boards' =>	$boards,
				)
			);

			list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
			$smcFunc['db_free_result']($request);

			while	($_REQUEST['start']	<	$max_thank_you_posts)
			{
				// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
				$increment = 250;

				// Okay	delete all this	posts
				$counter = $smcFunc['db_query']('',	"
					SELECT /*!40001	SQL_NO_CACHE */	id_msg
						FROM {db_prefix}thank_you_post
					WHERE	id_board IN	({array_int:boards})
						AND	id_msg > {int:start}
						AND	id_msg <=	{int:max_id}
					GROUP	BY id_msg",
					array(
						'start'	=> $_REQUEST['start'],
						'max_id' =>	$_REQUEST['start'] + $increment,
						'boards' =>	$boards,
					)
				);

				$rows	=	$smcFunc['db_num_rows']($counter);
				// Replace all
				$msg_ids = array();
				while	($row	=	$smcFunc['db_fetch_assoc']($counter))
					$msg_ids[] = $row['id_msg'];

				$smcFunc['db_free_result']($counter);

				// Delete	all, an	recallculate stats :)
				if (!empty($msg_ids))
					ThankYouPostDelete($msg_ids);

				$_REQUEST['start'] +=	$increment;

				if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
				{
					// Fix a possible	mistake	:P
					$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

					$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=maintain;activity=optimize;step=1;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
					$context['continue_percent'] = round((200	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

					return;
				}
			}
		}
		$_REQUEST['start'] = 0;
	}

	/*
	Find double	entries	but	only if	the	modSetting is	set...
	Each time	i	must goo through the complete	list...	so it	could	take longer	than thought :x
	This is	a	monster	array	request, depend	on your	server how fast	it is	:D
	*/
	if ($_REQUEST['step']	<= 2 &&	empty($modSettings['thankYouPostOnePerPost']))
	{
		$increment = 100;
		$maximum_retry = 20;

		// Maximum value,	the	new	system i go	through	topics step	by step	8)
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_topic)
			FROM {db_prefix}thank_you_post',
			array()
		);

		list ($max_thank_you_topics) = $smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_topics)
		{

			// Find	Members	to delete	:D
			$counter = $smcFunc['db_query']('',	'
				SELECT /*!40001	SQL_NO_CACHE */	id_member, COUNT(id_member)	as count,	id_topic
					FROM {db_prefix}thank_you_post
				WHERE	id_topic > {int:start}
					AND	id_topic <=	{int:max_id}
				GROUP	BY id_topic, id_member',
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);

			// Collect datas to	see	if the user	have some	double inserts :)
			$toMuch	=	array();
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				if ($row['count']	>	1)
					$toMuch[]	=	array(
						'id_member'	=> $row['id_member'],
						'id_topic' =>	$row['id_topic'],
						'count'	=> $row['count'],
						'limit'	=> $row['count'] - 1,
					);

			$smcFunc['db_free_result']($counter);

			// Double	insert found?
			if (!empty($toMuch))
			{
				foreach	($toMuch as	$toSearch)
				{
					// Mistake?	Normal this	user should	not	appear,	but	it's possible	:D
					if ($toSearch['count'] <=	1)
						continue;

					// Load	all	message	ids	of this	user,	but	leave	the	first	one	of the thread	:),	one	is allowe	you	now	it.
					$thx = $smcFunc['db_query']('',	"
						SELECT id_thx_post as	id_thx,	id_msg,	id_member
						FROM {db_prefix}thank_you_post
						WHERE	id_topic = {int:id_topic}
						LIMIT	1, {int:limit}",
						array(
							'id_topic' =>	$toSearch['id_topic'],
							'limit'	=> $toSearch['limit'],
						)
					);

					$remove_ids	=	array();
					while	($row	=	$smcFunc['db_fetch_assoc']($thx))
						$remove_ids[$row['id_msg']]	=	array(
							'id_thx' =>	$row['id_thx'],
							'id_member'	=> $row['id_member'],
						);

					$smcFunc['db_free_result']($thx);

					// Nothing to	do?	Okay my	mistake	go to	the	next :)
					if (empty($remove_ids))
						continue;

					// Next	Step...	single post	delete or	is it	a	complete delete	;),	it's a diffrence ;P
					$posts = $smcFunc['db_query']('',	'
						SELECT id_msg, id_member,	thank_you_post_counter
							FROM {db_prefix}messages
						WHERE	id_msg IN(array_int:id_msgs)
						LIMIT	{int:limit}',
						array(
							'id_msgs'	=> array_keys($remove_ids),
							'limit'	=> count(array_keys($remove_ids)),
						)
					);

					$toDelete	=	array(
						'single' =>	array(),
						'complete' =>	array(),
					);

					while	($row	=	$smcFunc['db_fetch_assoc']($posts))
					{
						if ($row['thank_you_post_counter'] ==	1)
							$toDelete['complete'][]	=	$row['id_msg'];
						else
							$toDelete['single'][]	=	array(
								'id_msg' =>	$row['id_msg'],
								'id_member_poster' =>	$row['id_member'],
								'id_thx' =>	$remove_ids[$row['id_msg']]['id_thx'],
								'id_member'	=> $remove_ids[$row['id_msg']]['id_member'],
							);
					}

					// Nothing to	do?	Hello... what	are	you	doing	:P
					if (empty($toDelete['complete']) &&	empty($toDelete['complete']))
					 continue;

					// Okay	remove complete	posts	:D
					if (!empty($toDelete['complete']))
						ThankYouPostDelete($toDelete['complete']);

					// Only	a	part of	it to	delete?	:D
					if (!empty($toDelete['single']))
					{
						// Okay	Step by	step *g*
						$msg_ids = array();
						$thx_ids = array();
						// First Step	decrase	all	became and made	stats	of the selected	members
						foreach	($toDelete['single'] as	$value)
						{
							$msg_ids[] = $value['id_msg'];
							$thx_ids[] = $value['id_thx'];
							// Update	Stats	:)
							updateMemberData($value['id_member'],	array('thank_you_post_made'	=> '-'));
							if (!empty($value['id_member_poster']) &&	$value['id_member_poster'] !=	'-1')
								updateMemberData($value['id_member_poster'], array('thank_you_post_became' =>	'-'));
						}

						// Remove	the	thx	ids
						if (!empty($thx_ids))
							$smcFunc['db_query']('', '
								DELETE FROM	{db_prefix}thank_you_post
								WHERE	id_thx_post	IN ({array_int:id_thxs})
								LIMIT	{int:limit}',
							array(
								'id_thxs'	=> $thx_ids,
								'limit'	=> count($thx_ids),
							)
						);

						// Recalculate the Complete	Sum	of the post	count	;) and reset the current counter :)
						if (!empty($msg_ids))
							ThankYouPostCount($msg_ids,	'reset');
					}
				}
			}

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_topics ? $max_thank_you_topics : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=maintain;activity=optimize;step=2;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
				$context['continue_percent'] = round((300	*	$currentValue	/	$max_thank_you_topics) / $total_steps);

				return;
			}
		}
	}

	// Find	enabled	Thank	You	Post but there are no	thank-o-matic	data...	delete them	and	remove them... can only	happen if	some delete	went wrong...
	if ($_REQUEST['step']	<= 3)
	{
		// Step	the	number of	topics at	a	time so	things don't time	out...
		$request = $smcFunc['db_query']('',	'
			SELECT MAX(id_msg)
			FROM {db_prefix}thank_you_post',
			array()
		);

		list ($max_thank_you_posts)	=	$smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);

		while	($_REQUEST['start']	<	$max_thank_you_posts)
		{
			// If	you	make this	higher value it	could	be faster	recount, please	do this	only if	you	now	what you do	:P
			$increment = 250;

			$counter = $smcFunc['db_query']('',	"
				SELECT /*!40001	SQL_NO_CACHE */	m.id_msg as	id_msg
				FROM {db_prefix}messages as	m
					LEFT JOIN	{db_prefix}thank_you_post	as t ON	(t.id_msg	=	m.id_msg)
				WHERE	t.id_msg IS	NULL
					AND	m.id_msg > {int:start}
					AND	m.id_msg <=	{int:max_id}",
				array(
					'start'	=> $_REQUEST['start'],
					'max_id' =>	$_REQUEST['start'] + $increment,
				)
			);

			$rows	=	$smcFunc['db_num_rows']($counter);
			// Replace all
			$msg_ids = array();
			while	($row	=	$smcFunc['db_fetch_assoc']($counter))
				$msg_ids[] = $row['id_msg'];

			$smcFunc['db_free_result']($counter);

			if (!empty($msg_ids))
				// Delete	all, need	no recalculation,	because	i	miss the master	things ;)
				$smcFunc['db_query']('', '
					UPDATE {db_prefix}messages
						SET thank_you_post_counter = 0, thank_you_post = 0
					WHERE	id_msg IN	({array_int:msg_ids})',
					array(
						'msg_ids' => $msg_ids,
					)
				);

			$_REQUEST['start'] +=	$increment;

			if (array_sum(explode('	', microtime())) - array_sum(explode(' ',	$time_start))	>	$minimumSeconds)
			{
				// Fix a possible	mistake	:P
				$currentValue	=	$_REQUEST['start'] > $max_thank_you_posts	?	$max_thank_you_posts : $_REQUEST['start'];

				$context['continue_get_data']	=	'?action=admin;area=maintainThankYouPost;sa=maintain;activity=optimize;step=3;start='	.	$_REQUEST['start'] . ';' . $context['session_var'] . '=' . $context['session_id'];
				$context['continue_percent'] = round((100	*	$currentValue	/	$max_thank_you_posts)	/	$total_steps);

				return;
			}
		}
		$_REQUEST['start'] = 4;
	}

	// Yeah	the	easiest	:P everthing that	have no	count	now, should	be disabled	=)
	if ($_REQUEST['step']	<= 4)
	{
		// Hope	you	fogive me	for	not	using	an array...	but	this is	strict :P
		$smcFunc['db_query']('', '
			UPDATE {db_prefix}messages
			SET	thank_you_post = 0
			WHERE	thank_you_post_counter = 0 AND thank_you_post	!= 0',
			array()
		);

		// Update	the	Last Thank You Post	Stats
		ThankYouPostUpdateLastThankYou();
	}

	// I should	find out how this	work and insert	it :D
	// Finally,	update the latest	event	times.
	// require_once($sourcedir . '/ScheduledTasks.php');
	// CalculateNextTrigger();

	redirectexit('action=admin;area=maintainThankYouPost;sa=maintain;done=optimize');
}
?>